package com.elinkway.infinitemovies.utils;

import android.os.StatFs;

import java.io.File;


public class StorageManager {
	/**
	 *  获得目录大小，返回long型 size
	 * @param directory
	 * @return
	 */
	public long getDirectorySize(File directory) {
	    File[] files = directory.listFiles();
	    long blockSize = getBlockSize(directory);
	    if (files != null) {
	    	long size=0;
	        for (File file : files) {
	            if (file.isDirectory()) {
	                // space used by subdirectory
	                size += getDirectorySize(file);
	            } else {
	                // file size need to rounded up to full block sizes
	                // (not a perfect function, it adds additional block to 0 sized files
	                // and file who perfectly fill their blocks) 
	                size += (file.length() / blockSize + 1) * blockSize;
	            }
	        }
	        return size;
	    } else {
	        return 0;
	    }
	}
	private long getBlockSize(File file){
		StatFs statFs = new StatFs(file.getAbsolutePath());
	    long blockSize;
	    blockSize=new CheckVersionToBlockSize().check(statFs);
	    return blockSize;
	}
	public static String bytes2humanity(long size){
		long h_size=size/1024;
		if(h_size<1024){
			return String.format("%dK", h_size);
		}
		else{
			float m_size = (float) (h_size/1024.0f);
			return String.format("%.1fM",m_size );
		}
	}
	class CheckVersionToBlockSize{
		public long check(StatFs statFs){
		        return statFs.getBlockSize();
		}
	}
}
